package top.maochang.hou.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class JDBCUtlis {

    //使用 DbUtils 操作数据库
    private static QueryRunner runner = new QueryRunner();

    /**
     * update() 方法用来执行：Insert\Update\Delete 语句
     * @return 如果返回-1,说明执行失败<br/>返回其他表示影响的行数
     */
    public static int update(String sql,Object ...ob) throws SQLException {
            System.out.println(" BaseDao 程序在[" +Thread.currentThread().getName() + "]中");
            Connection conn = DruidUtlis.getConnection();
            try {
                return  runner.update(conn, sql, ob);
            } catch (SQLException e) {
                e.printStackTrace();
                //这里不能在捕捉异常了得把异常往外抛
                throw new RuntimeException(e);
            }
    }

    /**
     * 查询单条记录
     */
    public static <T> T  queryForOne(Class<T> type,String sql,Object...ob){
        Connection conn = DruidUtlis.getConnection();
        try {
            //BeanHandler<>(type)数据类型：对象
            return  runner.query(conn,sql,new BeanHandler<>(type),ob);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询多条记录
     */
    public static <T> List<T> queryForList(Class<T> type,String sql,Object ...ob) throws SQLException {
        Connection conn = DruidUtlis.getConnection();
        try {
            return runner.query(conn,sql,new BeanListHandler<>(type),ob);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    /**
     * 查询多条记录
     * 解决DBUtils查询过程中数据库字段跟实体类字段不对应的问题
     */
    public static <T> List<T> queryForListBasicRowProcessor(Class<T> type, String sql, Map<String,String> map, Object ...ob){
        Connection conn=DruidUtlis.getConnection();
        try {
            return runner.query(conn,sql,new BeanListHandler<>(type,new BasicRowProcessor(new BeanProcessor(map))),ob);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理返回特殊结果值的方法：返回一行一列的
     */
    public static Object queryForSingleValue(String sql,Object ...ob){
        Connection conn=DruidUtlis.getConnection();
        try {
            return runner.query(conn,sql,new ScalarHandler(),ob);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
